<template>
  <div class="dynamic_table_item" >
    <a-upload
      v-model:file-list="fileList"
      :accept="props.question.state.accept"
      :name="props.question.state.name || 'file'"
      :disabled="isDisabled()"
      :max-count="props.question.state.maxCount || (props.question.state.multiple ? 10 : 1)"
      :multiple="props.question.state.multiple || false"
      :list-type="props.question.state.listType || 'picture-card'"
      class="avatar-uploader"
      :action="url"
      :headers="headers"
      :data="props.question.state.params"
      :customRequest="customUpload"
      :before-upload="beforeUpload"
      @change="handleChange"
      @success="handleSuccess"
      @preview="handlePreview"
      @remove="handleRemove"
    >
      <div v-if="props.question.type == 'static'"></div>
      <div v-else-if="props.question.state.listType == 'text'">
        <a-button>
          <!-- <upload-outlined /> -->
          <i class="iconfont icon-add"></i>
          上传文件
        </a-button>
        <p v-if="props.question.state.tip" style="margin-top: 10px">{{ props.question.state.tip }}</p>
      </div>
      <div v-else-if="fileList.length < (props.question.state.maxCount || (props.question.state.multiple ? 10 : 1))">
        <plus-outlined />
      </div>
    </a-upload>
    <p v-if="props.question.state.tip && !props.question.state.listType" style="margin: 0">{{ props.question.state.tip }}</p>
    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { watch, getCurrentInstance, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import { HOST } from '@/config';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useUserStoreWithOut } from '@/store/modules/user';
import { downloadFile, fileUrl, uploadFile, uploadUrl } from '@/config/api/common/api';
import { TABLEEVENTSERVE } from '@/mixins/subject/subject-types';
import { isHidden } from '@/utils';

const fileList: any = ref([]);
//subject变量
const { proxy  }:any = getCurrentInstance()
let props = defineProps<{ question: any;formData:any;dataForm?:any;index?:any }>();
const emit = defineEmits(['update:formData']);

const localValue:any = ref(null);

watch(
  () => localValue.value,
  (val) => {
    emit('update:formData', val);
  },
  { flush: 'sync' }
);
watch(
  () => props.formData,
  (val) => {
    if( props.formData !==  localValue.value){
      localValue.value = props.formData;
    }
  },
  { flush: 'sync' }
);

onMounted(() => {
  init();
});

//是否禁用
const isDisabled = ()=>{
  let disabled:boolean = false;
  if( Array.isArray(props.question.disabled)){
    disabled = isHidden(props.dataForm, { showKey: props.question.disabled });
    if( props.question.invertDisabled ){
      disabled = !disabled;
    }
  }else if( typeof props.question.disabled === 'boolean'  ){
    return props.question.disabled
  }else if( props.question.type == 'static' ){
    return true
  }
  return disabled
}

const init = () =>{
  localValue.value = props.formData;
  if (Array.isArray(localValue.value)) {
    fileList.value = localValue.value.map((item: any) => ({
      status: 'done',
      id: item,
      name: item,
      url: fileUrl(item)
    }));
  } else {
    if (localValue.value) {
      fileList.value = [{
        status: 'done',
        id: localValue.value,
        name: localValue.value,
        url: fileUrl(localValue.value)
      }];
    }
  }
}


const userStore = useUserStoreWithOut();
let accessToken: any = userStore.getToken;

const url = ref(`${props.question.state.url ? HOST + props.question.state.url : uploadUrl}`);
const headers = {
  token: `${accessToken}`
};

const loading = ref<boolean>(false);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

//查看图片
const handlePreview = async (file: any) => {
  console.log('input-upload.component.vue','handlePreview', file);
  if (!props.question.state.isImage) {
    return updateFile(file);
  }
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj, () => {});
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
// 下载文件
function updateFile(file) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', `${HOST}${props.question.state.viewUrl}/${file.name}`, true);
  xhr.setRequestHeader('token', accessToken);
  xhr.responseType = 'blob';
  xhr.onload = function (e) {
    //如果请求执行成功
    if (this.status == 200) {
      var blob = this.response;
      const nameStr = xhr.getResponseHeader('content-disposition') || '';
      const filename = nameStr.split('=')[1] || file.name;
      var a = document.createElement('a'); // blob.type = "application/octet-stream"; //创键临时url对象
      var url = URL.createObjectURL(blob);
      a.href = url;
      a.download = filename;
      a.click(); //释放之前创建的URL对象
      window.URL.revokeObjectURL(url);
    }
  }; //发送请求
  xhr.send();
}
const customUpload = (info:any)=>{
  console.log('自定义上传',info);
  uploadFile({ file: info.file }).then((res:any)=>{
    if( res && res.data ){
      if( props.question.state.multiple  ){
        fileList.value.push({
          status: 'done',
          name: res.data.name,
          id: res.data.id,
          url: fileUrl(res.data.id),
        });
      }else{
        fileList.value = [{
          status: 'done',
          name: res.data.name,
          id: res.data.id,
          url: fileUrl(res.data.id),
        }];
      }
      setValue();
      
    }
  })
}

//上传成功状态
const handleChange = (info: any) => {
  if( !isBeforeState.value ){
    fileList.value && fileList.value.length && fileList.value.splice(fileList.value.length-1,1);
    isBeforeState.value = true;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    // getBase64(info.file.originFileObj, (base64Url: string) => {
    //   localValue.value = base64Url;
    //   loading.value = false;
    // });
    // localValue.value = info.file.response.webUrl;
  }
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};

//查看图片
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};

//赋值
const setValue = () => {
  if (props.question.state.multiple) {
    //多个
    localValue.value = fileList.value.map((res: any) => res.id);
  } else {
    //单个
    localValue.value = fileList.value.length ? fileList.value[0].id : '';
  }
  proxy.$NotificationPubSub.pushParams({
    key: TABLEEVENTSERVE,
    value: {
      key: props.question.key,
      value: localValue.value,
      data: props.dataForm,
      index: props.index,
      name: props.question.state.name || props.question.name
    }
  });
};

//删除图片
const handleRemove = (file: any) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  setValue();
};

//上传成功
const handleSuccess = (e: any) => {
  fileList.value[fileList.value.length - 1].status = 'done';
  fileList.value[fileList.value.length - 1].id = e.data.id;
  fileList.value[fileList.value.length - 1].name = e.name;
  fileList.value[fileList.value.length - 1].url = `${HOST}${props.question.state.viewUrl}/${e.data.id}`;
  setValue();
};

//上传限制
const isBeforeState:any = ref(true);
const beforeUpload = (file: any) => {
  return new Promise((resolve, reject) => {
    if (props.question.state.isImage) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传JPG、png格式的文件!');
        isBeforeState.value = false;
        return reject(false);
      }
    }
    const isLt2M = file.size / 1024 / 1024 < (props.question.state.size || 4096);
    if (!isLt2M && !props.question.state.cancelLimit) {
      message.error(`上传文件大小不能大于${props.question.state.size?props.question.state.size+'M':'4G'}`);
      isBeforeState.value = false;
      return reject(false);
    }
    if(file.size === 0){
      message.error(`上传文件为空文件`);
      isBeforeState.value = false;
      return reject(false);
    }
    isBeforeState.value = true;
    return resolve(true);
  })
};
//图片
function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}
</script>

<style lang="less" scoped>
@import url('./input-upload.component.less');
</style>
